package com.link.play.fit.ai.utils

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.*
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.ui.SplashAc
import com.link.play.fit.ai.utils.DateEx.convertToDailyTimestamp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class DailyPushWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): Result {
        // 发送通知
        sendNotification()
        // 重新调度下一次
//        reschedule()
        return Result.success()
    }

    @SuppressLint("MissingPermission")
    private fun sendNotification() {
        val channelId = "kcal_meals_channel_id"
        val channelName = "kcal_meals_channel_name"
        "发送==========================".d()
        val notificationManager =
            applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            channel.setShowBadge(true)
            notificationManager.createNotificationChannel(channel)
        }

        val intent = Intent(applicationContext, SplashAc::class.java)
        val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        val notification = NotificationCompat.Builder(applicationContext, channelId)
            .setContentTitle("Kcal AI")
            .setContentIntent(pendingIntent)
            .setContentText(applicationContext.getString(com.link.play.fit.ai.R.string.do_you_typically_eat_your_meals_at_the_same_time_every_day))
            .setSmallIcon(com.link.play.fit.ai.R.mipmap.ic_launcher_round)
            .build()
        notificationManager.notify(Random.nextInt(), notification)
//        applicationContext.getSystemService(NotificationManager::class.java)
//            .notify(Random.nextInt(), notification)
//        NotificationCompat.Builder(applicationContext, channelId)
//            .setSmallIcon(R.mipmap.ic_launcher_round)
//            .setContentTitle("每日提醒")
//            .setContentText("现在是 ${getCurrentTime()}，请查看更新")
//            .setPriority(NotificationCompat.PRIORITY_HIGH)
//            .build()
//            .also {
//                NotificationManagerCompat.from(applicationContext)
//                    .notify(Random.nextInt(), it)
//            }
    }

    private fun reschedule() {
        val time = inputData.getString("TIME")
        var delay = 0L
        time?.let {
             delay = convertToDailyTimestamp(it) - System.currentTimeMillis()
        }

        val newWork = OneTimeWorkRequestBuilder<DailyPushWorker>()
            .setInitialDelay(delay, TimeUnit.MILLISECONDS)
            .setInputData(inputData)
            .build()

        WorkManager.getInstance(applicationContext)
            .enqueueUniqueWork(
                "daily_push_${delay}",
                ExistingWorkPolicy.REPLACE,
                newWork
            )
    }

    private fun getCurrentTime(): String {
        return SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date())
    }
}